package com.hdu.distributeLock.testController;


import com.hdu.distributeLock.lock.DistributeLockFactory;
import com.hdu.distributeLock.lock.DistributedRedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class TestController {

    private final DistributeLockFactory distributeLockFactory;


    public TestController(DistributeLockFactory distributeLockFactory) {
        this.distributeLockFactory = distributeLockFactory;
    }


    @GetMapping("lock/{lockName}")
    public String lock(@PathVariable String lockName) {
        DistributedRedisLock distributedRedisLock = distributeLockFactory.getDistributedRedisLock(lockName);
        if (distributedRedisLock.tryLock()) {
            log.info("获取锁成功");
            return "success";
        } else {
            log.error("获取锁失败");
            return "fail";
        }
    }

    @GetMapping("unlock/{lockName}")
    public String unLock(@PathVariable String lockName) {
        DistributedRedisLock distributedRedisLock = distributeLockFactory.getDistributedRedisLock(lockName);
        distributedRedisLock.unlock();
        return "success";
    }


    private void m1(String lockName) {
        DistributedRedisLock distributedRedisLock = distributeLockFactory.getDistributedRedisLock(lockName);
        if (distributedRedisLock.tryLock()) {
            log.info("获取锁成功");
            m2(lockName);
        } else {
            log.error("获取锁失败");
        }
    }

    private void m2(String lockName) {
        DistributedRedisLock distributedRedisLock = distributeLockFactory.getDistributedRedisLock(lockName);
        if (distributedRedisLock.tryLock()) {
            log.info("获取锁成功");
        } else {
            log.error("获取锁失败");
        }
    }

}
